package com.jinhuhang.u2.ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.*;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.jaeger.library.StatusBarUtil;
import com.jinhuhang.u2.MyApplication;
import com.jinhuhang.u2.R;
import com.jinhuhang.u2.activitysmodule.ActivityFragment;
import com.jinhuhang.u2.common.HomeWatcherReceiver;
import com.jinhuhang.u2.common.base.activity.SimpleBaseActivity;
import com.jinhuhang.u2.common.constant.Constant;
import com.jinhuhang.u2.entity.CheckActivity;
import com.jinhuhang.u2.entity.UserBean;
import com.jinhuhang.u2.homemodule.GestureActivity;
import com.jinhuhang.u2.homemodule.HomeFragment;
import com.jinhuhang.u2.invertmodule.InvertFragment;
import com.jinhuhang.u2.myselfmodule.MyAccountFragment;
import com.jinhuhang.u2.myselfmodule.engine.user.UserActivity;
import com.jinhuhang.u2.ui.customview.CustomToast;
import com.jinhuhang.u2.ui.mainview.MainContract;
import com.jinhuhang.u2.ui.mainview.MainPresenter;
import com.jinhuhang.u2.util.ShareDataUtil;
import com.jinhuhang.u2.util.StringUtils;
import com.jinhuhang.u2.util.http.HttpWrapper;
import com.jinhuhang.u2.util.http.HttpWrapperList;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import floatwindow.xishuang.float_lib.FloatActionController;

public class MainActivity extends SimpleBaseActivity implements MainContract.View,FloatActionController.SetLinstener {

    @Bind(R.id.home)
    LinearLayout mHome;
    @Bind(R.id.invert)
    LinearLayout mInvert;
    @Bind(R.id.account)
    LinearLayout mAccount;
    @Bind(R.id.activity)
    LinearLayout mActivity;
    @Bind(R.id.fragment)
    FrameLayout mFragment;
    @Bind(R.id.home_img1)
    ImageView mHomeImg1;
    @Bind(R.id.home_img2)
    ImageView mHomeImg2;
    @Bind(R.id.home_img3)
    ImageView mHomeImg3;
    @Bind(R.id.home_img4)
    ImageView mHomeImg4;

    //    @Bind(R.id.muti)
//    MutipleLayout mMuti;
    private FragmentManager mFragmentManager;
    private FragmentTransaction transaction;
    HomeFragment homefragment;
    InvertFragment invertFragment;
    MyAccountFragment myAccountFragment;
    ActivityFragment activityFragment;
    Map<String, Fragment> frameLayoutMap = new HashMap<>();

    public static String jumpActivity = "jumpActivity";
    public static String jumpInvert = "jumpInvert";
    public static String jumpHome = "jumpHome";
    public static String jumpAcount = "jumpAcount";

    MainContract.Presenter mPresenter;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(String event) {/* Do something */
        userbean = MyApplication.mSpUtil.getUser();
        if (event.equals(jumpActivity)) {
            if (userbean == null) {
                show = false;
                ;//浏览之后登陆
                Intent intent = new Intent(this, UserActivity.class);
                intent.putExtra("type", UserActivity.LOGIN);
                intent.putExtra("setType", GestureActivity.TYPE_activity);
                startActivity(intent);
            } else{
                checktoken=true;
                changeView(4);
            }
        } else if (event.equals(jumpInvert)) {
            changeView(2);
        } else if (event.equals(jumpHome)) {
            changeView(1);
        } else if (event.equals(jumpAcount)) {
            if (userbean == null) {
                show = false;
                Intent intent = new Intent(this, UserActivity.class);
                intent.putExtra("type", UserActivity.LOGIN);
                intent.putExtra("setType", GestureActivity.TYPE_account);
                startActivity(intent);
            } else {
                checktoken=true;
                changeView(3);
            }
        }
    }

    @Override
    protected void initView() {
        super.initView();
        registerHomeKeyReceiver();
        userbean = MyApplication.mSpUtil.getUser();
        int gesture = getIntent().getIntExtra("login", 0);
        if (gesture == 1) {
            show = false;
        }
        if (userbean != null && !StringUtils.isEmpty(userbean.getGestUrePassword())) {
            show = false;
        }
        EventBus.getDefault().register(this);
        mFragmentManager = getSupportFragmentManager();
        mHome.performClick();
        //setStatusBarDarkMode(true,MainActivity.this);
        mPresenter = new MainPresenter(this);

        showNotification(getIntent());
    }

    private static HomeWatcherReceiver mHomeKeyReceiver = null;

    private  void registerHomeKeyReceiver() {

        mHomeKeyReceiver = new HomeWatcherReceiver();
        final IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);

        registerReceiver(mHomeKeyReceiver, homeFilter);
    }

    private  void unregisterHomeKeyReceiver() {

        if (mHomeKeyReceiver != null) {
            unregisterReceiver(mHomeKeyReceiver);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main1;
    }

    public static UserBean userbean;
    public static String uid = "0";
    public static boolean checktoken=false;
    public static String tip =null;
    String name,pwd;//更新数据
    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        userbean = MyApplication.mSpUtil.getUser();
        if (userbean != null) {
            uid = userbean.getUserId();
            mPresenter.checkToken();
        } else {
            uid = "0";
        }
            mPresenter.getData();
        mPresenter.getPhone();
 //       mPresenter.checkActivity();
//        if (mCheckActivity!=null&& mCheckActivity.getStatus()!=0 &&mCheckActivity.getStatus()!=4) {
//
//            FloatActionController.getInstance().show();
//        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        showNotification(intent);
    }

    private void showNotification(Intent intent){
    int s=intent.getIntExtra("notif",0);
    String content=intent.getStringExtra("str");
    if (s==1){

        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(MainActivity.this);
        normalDialog.setIcon(R.mipmap.icon_youtu);
        normalDialog.setTitle("悠兔理财");
        normalDialog.setMessage(content);
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do

                    }
                });
        normalDialog.show();
    }
}
    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
//        if (mCheckActivity!=null&& mCheckActivity.getStatus()!=0 &&mCheckActivity.getStatus()!=4) {
//            FloatActionController.getInstance().hide();
//        }
    }

    @Override
    protected void onStop() {
        super.onStop();
//        if (mCheckActivity!=null&& mCheckActivity.getStatus()!=0 &&mCheckActivity.getStatus()!=4) {
//            FloatActionController.getInstance().hide();
//        }
    }

    @Override
    protected void ondestory() {
        super.ondestory();
//        if (mCheckActivity!=null&& mCheckActivity.getStatus()!=0 &&mCheckActivity.getStatus()!=4) {
//            FloatActionController.getInstance().stopMonkServer(this);
//        }

    }

    private int clickInto=0;
    @OnClick({R.id.home, R.id.invert, R.id.activity, R.id.account})
    void click(View view) {
        clickInto=0;
        switch (view.getId()) {
            case R.id.home:
                if (mCheckActivity!=null&& mCheckActivity.getStatus()!=0 &&mCheckActivity.getStatus()!=4) {
                    FloatActionController.getInstance().show();
                }
                changeView(1);
                break;
            case R.id.invert:
                if (mCheckActivity!=null&& mCheckActivity.getStatus()!=0 &&mCheckActivity.getStatus()!=4) {
                    FloatActionController.getInstance().show();
                }
                changeView(2);
                break;
            case R.id.activity:
                if (!checktoken || userbean==null) {
                    Constant.setGESture = 1;//浏览之后登陆
                    Intent intent = new Intent(this, UserActivity.class);
                    intent.putExtra("type", UserActivity.LOGIN);
                    intent.putExtra("setType", GestureActivity.TYPE_activity);
                    startActivity(intent);
                } else {
                    clickInto = 4;
                    mPresenter.checkToken1();
                }
                break;
            case R.id.account:
                if (!checktoken|| userbean==null) {
                    Constant.setGESture = 1;
                    Intent intent = new Intent(this, UserActivity.class);
                    intent.putExtra("type", UserActivity.LOGIN);
                    intent.putExtra("setType", GestureActivity.TYPE_account);
                    startActivity(intent);
                } else {
                    clickInto = 3;
                    mPresenter.checkToken1();
                }
                break;
        }

    }


    private void changeView(int lay) {
        transaction = mFragmentManager.beginTransaction();
        if (lay == 1) {
            changeNav(mHome);
            hideFragments(transaction, "homefragment");
            if (homefragment == null) {
                homefragment = new HomeFragment();
                frameLayoutMap.put("homefragment", homefragment);
                transaction.add(R.id.fragment, homefragment, "homefragment");
            }
        } else if (lay == 2) {
            changeNav(mInvert);
            hideFragments(transaction, "invertFragment");
            if (invertFragment == null) {
                invertFragment = new InvertFragment();
                frameLayoutMap.put("invertFragment", invertFragment);
                transaction.add(R.id.fragment, invertFragment, "invertFragment");
            }
        } else if (lay == 4) {
            changeNav(mActivity);
            hideFragments(transaction, "activityFragment");
            if (activityFragment == null) {
                activityFragment = new ActivityFragment();
                frameLayoutMap.put("activityFragment", activityFragment);
                transaction.add(R.id.fragment, activityFragment, "activityFragment");
            }
        } else if (lay == 3) {
            changeNav(mAccount);
            hideFragments(transaction, "myAccountFragment");
            if (myAccountFragment == null) {
                myAccountFragment = new MyAccountFragment();
                frameLayoutMap.put("myAccountFragment", myAccountFragment);
                transaction.add(R.id.fragment, myAccountFragment, "myAccountFragment");
            }
            //   myAccountFragment.initData();
        }
        transaction.commitAllowingStateLoss();
    }

    private void changeNav(View view) {
        mHome.setSelected(false);
        mInvert.setSelected(false);
        mAccount.setSelected(false);
        mActivity.setSelected(false);
        view.setSelected(true);
    }

    private void hideFragments(FragmentTransaction transaction, String tag) {
        for (Map.Entry<String, Fragment> fragementEntry : frameLayoutMap.entrySet()) {
            if (!fragementEntry.getKey().equals(tag)) {
                Fragment currentFragment = fragementEntry.getValue();
                transaction.hide(currentFragment);
            }
        }

        Fragment currentFragment = frameLayoutMap.get(tag);
        if (currentFragment != null) {
            transaction.show(currentFragment);
        }
    }


    private long exitTime = 0l;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {

            if ((System.currentTimeMillis() - exitTime) > 2000) {
                CustomToast.showToast("再次点击退出");
                exitTime = System.currentTimeMillis();
            } else {
                homefragment = null;
                invertFragment = null;
                myAccountFragment = null;
                activityFragment = null;
                finish();
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unregisterHomeKeyReceiver();
    }

    @Override
    protected void setStatusBar() {
        StatusBarUtil.setTranslucentForImageViewInFragment(this, null);
    }

    private ProgressDialog progressDialog;
    private Handler handler;

    @Override
    public void install(Uri uri) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        startActivity(intent);
    }

    @Override
    public void check(String v1) {
        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("版本更新提示");
        progressDialog.setMessage("有新版本正在更新，请您等待");
        progressDialog.setCancelable(false);
        progressDialog.setIndeterminate(false);
        progressDialog.show();

    }

    @Override
    public void progressNUM(int progress) {
        if (progress >= 100) {
            progressDialog.cancel();
        }
    }


    @Override
    public void onResultLogin(HttpWrapper<UserBean> data) {
        if(Constant.SUCCESS_CODE == data.code){
            /**
             * TODO  保存User数据
             */
            userbean=data.getData();
            userbean.setUserName(name);
            userbean.setLoginPwd(pwd);
            MyApplication.mSpUtil.setUser(userbean);
        }else {
            MyApplication.mSpUtil.setUser(null);
            userbean=null;
            uid = "0";
        }
    }
    CheckActivity mCheckActivity;
    @Override
    public void startActivity(CheckActivity activity) {
        mCheckActivity=activity;
        if (activity.getStatus()!=0){
            int show=ShareDataUtil.getInt("showdialog",0);//0未弹过 1 未登录弹一次，登录后由服务端确定
            if (show==0) {
                showDialog(this, activity.getActivityUrl(), activity.getTitle());
                if (uid.equals("0")){
                    ShareDataUtil.putInt("showdialog",1);
                }
//                else {
//                    ShareDataUtil.putInt("showdialog",2);
//                }
            }else if (show==1){
                if (!uid.equals("0")){
                    showDialog(this, activity.getActivityUrl(), activity.getTitle());
                  //  ShareDataUtil.putInt("showdialog",2);
                }
            }
        }else {

        }
    }

    @Override
    public void checkTokenResult() {
        MainActivity.checktoken=true;
        name=userbean.getUserName();
        pwd=userbean.getLoginPwd();
        Map<String,String> map = new HashMap<>();
        map.put("username",userbean.getUserName());
        map.put("userId", Constant.DEFAULT_USER_ID);
        map.put("password",userbean.getLoginPwd());
        map.put("loginType",Constant.PLATFORM);
        map.put("token",userbean.getToken());
        mPresenter.Login(map);
    }

    @Override
    public void jumpTo(HttpWrapperList<String> o) {
        if (o.getCode()==200){
            checktoken=true;
            if (clickInto==3) {
                changeView(3);
            }else
            if (clickInto==4) {
                changeView(4);
            }
        }
        else {
            checktoken=false;
            if (!checktoken|| userbean==null) {
                Constant.setGESture = 1;
                if (userbean!=null){
                    MyApplication.mSpUtil.setUser(null);
                    if (o.getCode()!=301) {
                        CustomToast.showToast(o.getInfo());
                    }
                }
                if (clickInto==3) {
                    Intent intent = new Intent(this, UserActivity.class);
                    intent.putExtra("type", UserActivity.LOGIN);
                    intent.putExtra("setType", GestureActivity.TYPE_account);
                    startActivity(intent);
                }else
                if (clickInto==4) {
                    Intent intent = new Intent(this, UserActivity.class);
                    intent.putExtra("type", UserActivity.LOGIN);
                    intent.putExtra("setType", GestureActivity.TYPE_activity);
                    startActivity(intent);
                }

            }
        }

    }

    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 1) {
                FloatActionController.getInstance().setstr(mCheckActivity.getStatus() + "");
            }
            else if (msg.what == 2) {
                FloatActionController.getInstance().setstr(mCheckActivity.getStatus() + "");
                FloatActionController.getInstance().stopMonkServer(MainActivity.this);
            }
            return false;
        }
    });
    @Override
    public void setPresenter(MainContract.Presenter presenter) {

    }


    @Override
    public void setjump() {
        Intent intent = new Intent(this, WebViewActivity.class);

        intent.putExtra("title", mCheckActivity.getTitle());
        String str=mCheckActivity.getActivityUrl().replace("userId=0","userId="+MainActivity.uid);;
        intent.putExtra("webAddress",str);
        startActivity(intent);
    }
    Dialog dialog =null;
    public  void showDialog(final Context context,String url,String title) {
        if(dialog!=null){
            mPresenter.setRead();
            dialog.cancel();
        }
        View view =   LayoutInflater.from(context).inflate(R.layout.activity_dialog,null);
        ImageView close =  (ImageView) view.findViewById(R.id.showview_close);
        ImageView look =  (ImageView) view.findViewById(R.id.look_bill);
        dialog =  new Dialog(context, R.style.dialog);
        final WindowManager.LayoutParams lp=dialog.getWindow().getAttributes();
        lp.alpha=1.0f;
        dialog.setCanceledOnTouchOutside(false);
        dialog.getWindow().setAttributes(lp);
        dialog.setContentView(view);
        dialog.show();
        close.setOnClickListener(view1->{
            if (!uid.equals("0")){
                mPresenter.setRead();
            }
            dialog.dismiss();
        });
        look.setOnClickListener(view2->{
            if (!uid.equals("0")){
                mPresenter.setRead();
            }
            Intent intent = new Intent(context, WebViewActivity.class);
            intent.putExtra("webAddress", url.replace("userId=0","userId="+MainActivity.uid));
            intent.putExtra("title", title);
            context.startActivity(intent);
            dialog.dismiss();
        });
    }
}
